package com.sdkx.app.dialog;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sdkx.app.R;
import com.sdkx.app.model.AirSpace;
import com.sdkx.app.model.AirSpacePoint;
import com.sdkx.app.util.ToastUtil;
import com.sdkx.app.util.Util;
import com.sdkx.app.view.BrokenLineView;
import com.sdkx.app.view.DegreeInputView;

import java.util.ArrayList;
import java.util.List;

public class AirSpaceDialog extends Dialog implements View.OnClickListener {
    AirSpace airSpace;
    int option = 0;
    TextView titlename;
    TextView spacename;
    BrokenLineView styleimg;
    IBaseTypeView iBaseTypeView;


    IASCallback iasCallback;

    public AirSpaceDialog(@NonNull Context context, int option) {
        super(context);
        this.option = option;
        init();
    }

    public AirSpaceDialog(@NonNull Context context, AirSpace space) {
        super(context);
        airSpace = space;
        this.option = airSpace.getType();
        init();
    }

    public void init() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        View contentview = getLayoutInflater().inflate(R.layout.airspace_info_layout, null);
        setContentView(contentview);
        spacename = contentview.findViewById(R.id.name);
        titlename = contentview.findViewById(R.id.title);
        contentview.findViewById(R.id.brokenimg_parent).setOnClickListener(this);
        styleimg = contentview.findViewById(R.id.brokenimg);
        contentview.findViewById(R.id.importfile).setOnClickListener(this);
        contentview.findViewById(R.id.save).setOnClickListener(this);
        initRoundtype(contentview, airSpace);
        if (airSpace != null) {
            styleimg.setLineColor(airSpace.getLinecolor());
            styleimg.setLineWidth(airSpace.getLinewidth());
            spacename.setText(airSpace.getName());
            styleimg.setLineWidth(airSpace.getLinewidth());
            styleimg.setLineColor(airSpace.getLinecolor());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.brokenimg_parent:
                LineColorDialog dialog = new LineColorDialog(getContext());
                if (airSpace != null) {
                    dialog.setColor(airSpace.getLinecolor());
                    dialog.setLineWidth(airSpace.getLinewidth());
                } else {
                    dialog.setColor(styleimg.getLineColor());
                    dialog.setLineWidth(styleimg.getLineWidth());
                }
                dialog.setColorCallback(new LineColorDialog.ICallback() {
                    @Override
                    public void onCallBack(int color, int width, Bitmap bitmap) {
                        if (airSpace == null)
                            airSpace = new AirSpace();
                        airSpace.setLinewidth(width);
                        airSpace.setLinecolor(color);
                        styleimg.setLineWidth(width);
                        styleimg.setLineColor(color);
                        styleimg.postInvalidate();
                        bitmap.recycle();
                    }
                });
                dialog.show();
                break;
            case R.id.save:
                String name = spacename.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    ToastUtil.show(getContext(), "名称不能为空", Gravity.CENTER);
                    return;
                }
                if (airSpace == null)
                    airSpace = new AirSpace();
                if (iBaseTypeView != null && !iBaseTypeView.storeUIAsInfo(airSpace))
                    return;
                airSpace.setName(name);
                airSpace.setType(option);
                airSpace.setLinecolor(styleimg.getLineColor());
                airSpace.setLinewidth(styleimg.getLineWidth());
                airSpace.save();
                notifyData(airSpace);
                dismiss();
                break;
            case R.id.importfile:
                break;

        }
    }

    private void initRoundtype(View contentview, AirSpace space) {
        switch (option) {
            case AirSpace.TYPE_POLYGON:
                iBaseTypeView = new PolygonStyleView();
                titlename.setText("多边形空域");
                break;
            case AirSpace.TYPE_ROUND:
                titlename.setText("圆形空域");
                iBaseTypeView = new RoundStyleView();
                break;
        }
        iBaseTypeView.init(contentview, space);
    }


    private interface IBaseTypeView {
        void init(View parent, AirSpace space);

        boolean storeUIAsInfo(AirSpace space);
    }

    private class RoundStyleView implements IBaseTypeView {
        ViewStub roundtub;
        DegreeInputView latview, lonview;
        EditText editRadius;
        AirSpacePoint airSpacePoint;

        @Override
        public void init(View parent, AirSpace space) {
            roundtub = parent.findViewById(R.id.roundstub);
            View view = roundtub.inflate();
            latview = view.findViewById(R.id.lat);
            lonview = view.findViewById(R.id.lon);
            editRadius = view.findViewById(R.id.radius);
            if (space != null && space.getPointsIndb().size() > 0) {
                airSpacePoint = space.getPointsIndb().get(0);
                lonview.setTextEx(Util.degreePatten(getContext(), airSpacePoint.getLongitude()));
                latview.setTextEx(Util.degreePatten(getContext(), airSpacePoint.getLatitude()));
                editRadius.setText(airSpacePoint.getRadius() + "");
            }
        }

        @Override
        public boolean storeUIAsInfo(AirSpace space) {
            if (airSpace == null) return false;
            String radius = editRadius.getText().toString();
            if (latview.checkillegal()) {
                ToastUtil.show(getContext(), "纬度数据不正确", Gravity.CENTER);
                return false;
            }
            if (lonview.checkillegal()) {
                ToastUtil.show(getContext(), "经度数据不正确", Gravity.CENTER);
                return false;
            }
            if (TextUtils.isEmpty(radius)) {
                ToastUtil.show(getContext(), "半径不能为空", Gravity.CENTER);
                return false;
            }

            if (airSpacePoint == null)
                airSpacePoint = new AirSpacePoint();
            airSpacePoint.setLatitude(latview.toDegree());
            airSpacePoint.setLongitude(lonview.toDegree());
            airSpacePoint.setRadius(Float.valueOf(radius));
            if (airSpacePoint.getId() > 0) {
                airSpacePoint.update(airSpacePoint.getId());
            } else
                airSpacePoint.save();
            space.getPoints().add(airSpacePoint);
            return true;
        }
    }

    private class PolygonStyleView implements IBaseTypeView, View.OnClickListener {
        ViewStub polygonstub;
        RecyclerView recyclerView;
        PolygonAdapter polygonAdapter;

        @Override
        public void init(View parent, AirSpace space) {
            polygonstub = parent.findViewById(R.id.polygonstub);
            View view = polygonstub.inflate();
            recyclerView = view.findViewById(R.id.recyclerView);
            view.findViewById(R.id.add).setOnClickListener(this);
            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
            polygonAdapter = new PolygonAdapter();
            recyclerView.setAdapter(polygonAdapter);
            if (null != space) {
                polygonAdapter.setList(space.getPointsIndb());
            }
        }

        @Override
        public boolean storeUIAsInfo(AirSpace space) {
            if (polygonAdapter.getList() == null || polygonAdapter.getList().size() <3) {
                ToastUtil.show(getContext(), "请添加三个以上的经纬度点信息", Gravity.CENTER);
                return false;
            }
            if (airSpace == null)
                airSpace = new AirSpace();
            for (AirSpacePoint point : polygonAdapter.getList()) {
                if (point.getId() > 0)
                    point.update(point.getId());
                else
                    point.save();
            }
            airSpace.getPoints().addAll(polygonAdapter.getList());
            return true;
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.add:
                    final InnerDialog innerdialog = new InnerDialog(getContext());
                    View view = getLayoutInflater().inflate(R.layout.lonlat_inputlayout, null);
                    final DegreeInputView lonedit = view.findViewById(R.id.lon);
                    final DegreeInputView latedit = view.findViewById(R.id.lat);

                    view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            innerdialog.dismiss();
                        }
                    });
                    view.findViewById(R.id.confirm).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (latedit.checkillegal()) {
                                ToastUtil.show(getContext(), "纬度不正确", Gravity.CENTER);
                                return;
                            }
                            if (lonedit.checkillegal()) {
                                ToastUtil.show(getContext(), "经度不正确", Gravity.CENTER);
                                return;
                            }
                            AirSpacePoint point = new AirSpacePoint();
                            point.setLongitude(lonedit.toDegree());
                            point.setLatitude(latedit.toDegree());

                            polygonAdapter.getList().add(point);
                            polygonAdapter.notifyDataSetChanged();
                            innerdialog.dismiss();
                        }
                    });
                    innerdialog.setContentView(view);
                    innerdialog.show();
                    break;
            }
        }
    }

    private class InnerDialog extends Dialog {

        public InnerDialog(@NonNull Context context) {
            super(context);
            getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
    }

    public class PolygonAdapter extends RecyclerView.Adapter<PolygonAdapter.ViewHolder> {
        public List<AirSpacePoint> getList() {
            return list;
        }

        public void setList(List<AirSpacePoint> list) {
            this.list = list;
        }

        List<AirSpacePoint> list = new ArrayList<>();

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = getLayoutInflater().inflate(R.layout.airspace_lonlat_item, null);
            view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            holder.init(list.get(position), position);
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            AirSpacePoint mPoint;
            TextView lon, lat, number;

            public ViewHolder(View itemView) {
                super(itemView);
                lon = itemView.findViewById(R.id.lon);
                lat = itemView.findViewById(R.id.lat);
                number = itemView.findViewById(R.id.number);
                number.setVisibility(View.VISIBLE);
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AlertDialog alertDialog = new AlertDialog.Builder(getContext(), AlertDialog.THEME_TRADITIONAL)
                                .setMessage("是否删除节点" + number.getText().toString())
                                .setPositiveButton("确定", new OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        list.remove(mPoint);
                                        mPoint.delete();
                                        notifyDataSetChanged();
                                    }
                                })
                                .setNegativeButton("取消", new OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .create();
                        alertDialog.show();
                    }
                });
            }

            public void init(AirSpacePoint point, int pos) {
                mPoint = point;
                lon.setText(Util.degreePatten(getContext(), point.getLongitude()));
                lat.setText(Util.degreePatten(getContext(), point.getLatitude()));
                number.setText(String.valueOf(++pos));
            }
        }
    }

    public interface IASCallback {
        void onSave(AirSpace airSapce);
    }

    public void setIasCallback(IASCallback iasCallback) {
        this.iasCallback = iasCallback;
    }

    private void notifyData(AirSpace airSpace) {
        if (iasCallback != null)
            iasCallback.onSave(airSpace);
    }
}
